<template>
  <div :class="layoutCls">
    <t-head-menu ref="headMenuRef" :class="menuCls" :theme="menuTheme" expand-type="popup" :value="active">
      <template #logo>
        <span v-if="showLogo" class="header-logo-container" @click="handleNav('/dashboard/base')">
          <!-- <logo-full class="t-logo" /> -->
          <img src="@/assets/assets-logo-full.png" class="t-logo" alt="Logo" />
        </span>
        <div v-else class="header-operate-left">
          <t-button theme="default" shape="square" variant="text" @click="changeCollapsed">
            <t-icon class="collapsed-icon" name="view-list" />
          </t-button>
          <search :layout="layout" />
        </div>
      </template>
      <template v-if="layout !== 'side'" #default>
        <t-button v-if="isShowMenuBtn" shape="circle" variant="text" @click="handleMenuContentScroll('left')">
          <template #icon>
            <t-icon name="chevron-left" />
          </template>
        </t-button>
        <menu-content class="header-menu" :nav-data="menu" :style="{ width: menuContentWidth }" />
        <t-button v-if="isShowMenuBtn" shape="circle" variant="text" @click="handleMenuContentScroll('right')">
          <template #icon>
            <t-icon name="chevron-right" />
          </template>
        </t-button>
      </template>
      <template #operations>
        <div class="operations-container">
          <!-- 搜索框 -->
          <!-- <search v-if="layout !== 'side'" :layout="layout" /> -->
          <!-- 全局通知 -->
          <!-- <notice /> -->
          <!-- <t-tooltip placement="bottom" :content="t('layout.header.code')">
            <t-button theme="default" shape="square" variant="text" @click="navToGitHub">
              <t-icon name="logo-github" />
            </t-button>
          </t-tooltip> -->
          <!-- <t-tooltip placement="bottom" :content="t('layout.header.help')">
            <t-button theme="default" shape="square" variant="text" @click="navToHelper">
              <t-icon name="help-circle" />
            </t-button>
          </t-tooltip> -->
          <!-- <t-dropdown trigger="click">
            <t-button theme="default" shape="square" variant="text">
              <translate-icon />
            </t-button>
            <t-dropdown-menu>
              <t-dropdown-item
                v-for="(lang, index) in langList"
                :key="index"
                :value="lang.value"
                @click="(options) => changeLang(options.value as string)"
              >
                {{ lang.content }}
              </t-dropdown-item>
            </t-dropdown-menu>
          </t-dropdown> -->
          <t-dropdown :min-column-width="120" trigger="click">
            <template #dropdown>
              <t-dropdown-menu>
                <t-dropdown-item class="operations-dropdown-container-item" @click="handleUpdatePassword">
                  <RotateLockedIcon />{{ t('layout.header.user') }}
                </t-dropdown-item>
                <t-dropdown-item class="operations-dropdown-container-item" @click="handleLogout">
                  <poweroff-icon />{{ t('layout.header.signOut') }}
                </t-dropdown-item>
              </t-dropdown-menu>
            </template>
            <t-button class="header-user-btn" theme="default" variant="text">
              <template #icon>
                <t-icon class="header-user-avatar" name="user-circle" />
              </template>
              <div class="header-user-account">{{ user.userInfo.nickname }}</div>
              <template #suffix><chevron-down-icon /></template>
            </t-button>
          </t-dropdown>
          <!-- <t-tooltip placement="bottom" :content="t('layout.header.setting')">
            <t-button theme="default" shape="square" variant="text" @click="toggleSettingPanel">
              <setting-icon />
            </t-button>
          </t-tooltip> -->
        </div>
      </template>
    </t-head-menu>
      <!-- 自定义对话框 -->
    <custom-dialog ref="customDialogRef" v-slot="{ formData }" :api-map="{ update: updateUserPassword }" header="修改密码" @request-success="handleDialogRequestSuccess"   :update-sucess-tip="'密码修改成功，请重新登录'">
      <t-form-item label="旧密码" name="oldPassword" :rules="[{ required: true, message: '请输入旧密码' }]">
        <t-input v-model:value="formData.oldPassword" placeholder="请输入旧密码" clearable type="password" />
      </t-form-item>
      <t-form-item 
    label="新密码" 
    name="newPassword" 
    help="密码需包含英文字母、数字和特殊字符，至少8位"
    :rules="[
      { required: true, message: '请输入新密码' },
      { 
        validator: (val) => validatePassword(val, formData), 
        message: '密码强度不足' // 这个message会被自定义验证器覆盖
      }
    ]"
  >
    <t-input v-model:value="formData.newPassword" placeholder="请输入新密码" clearable type="password" />
    
  </t-form-item>
  
  
  <t-form-item 
    label="确认密码" 
    name="confirmPassword" 
    :rules="[
      { required: true, message: '请输入确认密码' },
      { 
        validator: (val) => val === formData.newPassword, 
        message: '两次输入的密码不一致' 
      }
    ]"
  >
    <t-input v-model:value="formData.confirmPassword" placeholder="请输入确认密码" clearable type="password" />
  </t-form-item>
    </custom-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  ChevronDownIcon,
  PoweroffIcon,
  //  SettingIcon,
  //  TranslateIcon,
  UserCircleIcon,
  RotateLockedIcon
} from 'tdesign-icons-vue-next';
import type { PropType } from 'vue';
import { computed, nextTick, ref, useTemplateRef } from 'vue';
import { useRouter } from 'vue-router';

import LogoFull from '@/assets/assets-logo-full.svg?component';
import { prefix } from '@/config/global';
import { t } from '@/locales';
// import { langList } from '@/locales/index';
// import { useLocale } from '@/locales/useLocale';
import { getActive } from '@/router';
import { useSettingStore, useUserStore } from '@/store';
import type { MenuRoute, ModeType } from '@/types/interface';

import MenuContent from './MenuContent.vue';
// import Notice from './Notice.vue';
import Search from './Search.vue';
import CustomDialog from '@/components/custom/dialog/index.vue';

import { updateUserPassword } from '@/api/system/user';

const props = defineProps({
  theme: {
    type: String,
    default: 'light',
  },
  layout: {
    type: String,
    default: 'top',
  },
  showLogo: {
    type: Boolean,
    default: true,
  },
  menu: {
    type: Array as PropType<MenuRoute[]>,
    default: () => [],
  },
  isFixed: {
    type: Boolean,
    default: false,
  },
  isCompact: {
    type: Boolean,
    default: false,
  },
  maxLevel: {
    type: Number,
    default: 3,
  },
});

const router = useRouter();
const settingStore = useSettingStore();
const user = useUserStore();

// const toggleSettingPanel = () => {
//   settingStore.updateConfig({
//     showSettingPanel: true,
//   });
// };

const active = computed(() => getActive());

const layoutCls = computed(() => [`${prefix}-header-layout`]);

const menuCls = computed(() => {
  const { isFixed, layout, isCompact } = props;
  return [
    {
      [`${prefix}-header-menu`]: !isFixed,
      [`${prefix}-header-menu-fixed`]: isFixed,
      [`${prefix}-header-menu-fixed-side`]: layout === 'side' && isFixed,
      [`${prefix}-header-menu-fixed-side-compact`]: layout === 'side' && isFixed && isCompact,
    },
  ];
});
const menuTheme = computed(() => props.theme as ModeType);

// 切换语言
// const { changeLocale } = useLocale();
// const changeLang = (lang: string) => {
//   changeLocale(lang);
// };

const changeCollapsed = () => {
  settingStore.updateConfig({
    isSidebarCompact: !settingStore.isSidebarCompact,
  });
};

const handleNav = (url: string) => {
  router.push(url);
};

const handleLogout = () => {
  router.push({
    path: '/login',
    // query: { redirect: encodeURIComponent(router.currentRoute.value.fullPath) },
  });
};
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
const handleUpdatePassword = () => {
  customDialogRef.value.open('update', {});
}
const handleDialogRequestSuccess = () =>{
  handleLogout();
}
type TDesignValidateResult = {
  result: boolean;
  message?: string;
  type?: 'error' | 'success' | 'warning'; // 严格限制为这三个值
};
// 密码强度验证函数
const validatePassword = (value: string): TDesignValidateResult => {
  // 至少8位
  if (value.length < 8) {
    return {
      result: false,
      message: '密码至少需要8位',
      type: 'error'
    };
  }
  // 包含英文字母（不区分大小写）
  if (!/[a-zA-Z]/.test(value)) {
    return {
      result: false,
      message: '密码必须包含英文字母',
      type: 'error'
    };
  }
  // 包含数字
  if (!/\d/.test(value)) {
    return {
      result: false,
      message: '密码必须包含数字',
      type: 'error'
    };
  }
  // 包含特殊字符
  if (!/[!@#$%^&*(),.?":{}|<>]/.test(value)) {
    return {
      result: false,
      message: '密码必须包含特殊字符',
      type: 'error'
    };
  }
  return { result: true };
};
// const navToGitHub = () => {
//   window.open('https://github.com/tencent/tdesign-vue-next-starter');
// };

// const navToHelper = () => {
//   window.open('http://tdesign.tencent.com/starter/docs/get-started');
// };

const headMenuRef = ref();
const menuContentWidth = computed(() => {
  const headMenuChildren = headMenuRef.value?.$el.children[0].children || [];
  const w1 = headMenuChildren[0]?.offsetWidth;
  const w2 = headMenuChildren[2]?.offsetWidth;
  if (w1 && w2) return `calc(100vw - ${w1 + w2 + 130}px)`;
  return 0;
});

const isShowMenuBtn = ref(false);
nextTick(() => {
  const element = window.document.getElementsByClassName('header-menu')[0];
  if (element?.scrollWidth > element?.clientWidth) isShowMenuBtn.value = true;
});

const handleMenuContentScroll = (direction: 'left' | 'right') => {
  const element = window.document.getElementsByClassName('header-menu')[0];
  const distance = element.scrollLeft;
  const step = 200;
  element.scrollTo({
    left: { left: distance - step, right: distance + step }[direction],
    behavior: 'smooth',
  });
};
</script>
<style lang="less" scoped>
.@{starter-prefix}-header {
  &-menu-fixed {
    position: fixed;
    top: 0;
    z-index: 1001;

    :deep(.t-head-menu__inner) {
      padding-right: var(--td-comp-margin-xl);
    }

    &-side {
      left: 232px;
      right: 0;
      z-index: 10;
      width: auto;
      transition: all 0.3s;

      &-compact {
        left: 64px;
      }
    }
  }

  &-logo-container {
    cursor: pointer;
    display: inline-flex;
  }
}

.header-menu {
  flex: 1 1 1;
  display: inline-flex;
  overflow: scroll hidden;
  padding-top: 8px;

  &::-webkit-scrollbar {
    height: 8px;
    background: transparent;
  }

  &::-webkit-scrollbar-thumb {
    border-radius: 6px;
    border: 2px solid transparent;
    background-clip: content-box;
    background-color: var(--td-scrollbar-color);
  }

  :deep(.t-menu__item) {
    min-width: unset;
  }
}

.operations-container {
  display: flex;
  align-items: center;

  .t-popup__reference {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .t-button {
    margin-left: var(--td-comp-margin-l);
  }
}

.header-operate-left {
  display: flex;
  align-items: normal;
  line-height: 0;
}

.header-logo-container {
  width: 250px;
  height: 38px;
  display: flex;
  margin-left: 0px;
  color: var(--td-text-color-primary);

  .t-logo {
    width: 100%;
    height: 100%;

    &:hover {
      cursor: pointer;
    }
  }

  &:hover {
    cursor: pointer;
  }
}

.header-user-account {
  display: inline-flex;
  align-items: center;
  color: var(--td-text-color-primary);
}

:deep(.t-head-menu__inner) {
  border-bottom: 1px solid var(--td-component-stroke);
}

.t-menu--light {
  .header-user-account {
    color: var(--td-text-color-primary);
  }
}

.t-menu--dark {
  .t-head-menu__inner {
    border-bottom: 1px solid var(--td-gray-color-10);
  }

  .header-user-account {
    color: rgb(255 255 255 / 55%);
  }
}

.operations-dropdown-container-item {
  width: 100%;
  display: flex;
  align-items: center;

  :deep(.t-dropdown__item-text) {
    display: flex;
    align-items: center;
  }

  .t-icon {
    font-size: var(--td-comp-size-xxxs);
    margin-right: var(--td-comp-margin-s);
  }

  :deep(.t-dropdown__item) {
    width: 100%;
    margin-bottom: 0;
  }

  &:last-child {
    :deep(.t-dropdown__item) {
      margin-bottom: 8px;
    }
  }
}
.password-hint {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}
</style>

<!-- eslint-disable-next-line vue-scoped-css/enforce-style-type -->
<style lang="less">
.operations-dropdown-container-item {
  .t-dropdown__item-text {
    display: flex;
    align-items: center;
  }
}
</style>
